"""
存放各种 响应的xml模板
"""

import json
import datetime

from pathlib import Path
from urllib.parse import quote
from typing import List, Optional

from data.global_var import STORAGE_DIR


# 策略模板
def policy_xml(bucket):
    # 构建策略内容
    policy = {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Principal": "*",
                "Action": "s3:GetObject",
                "Resource": f"arn:aws:s3:::{bucket}/*"
            }
        ]
    }

    # 构建响应
    return f'''<?xml version="1.0" encoding="UTF-8"?>
<GetBucketPolicyResult>
   <Policy>{json.dumps(policy)}</Policy>
</GetBucketPolicyResult>'''


# 生成 ListObjects 的 XML 响应内容
def generate_list_objects_response_back(bucket: str, objects: List[str], prefix: str, delimiter: str, max_keys: int,
                                        is_truncated: bool, next_marker: Optional[str] = None):
    """
    生成 ListObjects 的 XML 响应内容
    """
    content = f"""
    <ListBucketResult>
        <Name>{bucket}</Name>
        <Prefix>{bucket}</Prefix>
        <Marker></Marker>
        <MaxKeys>{max_keys}</MaxKeys>
        <IsTruncated>{'true' if is_truncated else 'false'}</IsTruncated>
    """
    if next_marker:
        content += f"<NextMarker>{next_marker}</NextMarker>"

    for obj in objects:
        obj = Path(STORAGE_DIR) / bucket / obj
        last_modified = datetime.datetime.fromtimestamp(obj.stat().st_mtime).strftime(
            '%Y-%m-%dT%H:%M:%SZ')  # 最后修改时间'%Y-%m-%dT%H:%M:%SZ'
        content += f"""
        <Contents>
            <Key>{quote(bucket + '/' + obj.name)}</Key>
            <LastModified>{last_modified}</LastModified>
            <ETag>"1234567890abcdef"</ETag>
            <Size>{obj.stat().st_size}</Size>
            <StorageClass>STANDARD</StorageClass>
            <Owner>
                <ID>qwe159357</ID>
                <DisplayName>83241568@qq.com</DisplayName>
            </Owner>
        </Contents>
        """

    content += "</ListBucketResult>"
    return content


def generate_list_objects_response(bucket: str, objects: List[str], prefix: str, delimiter: str, max_keys: int,
                                   is_truncated: bool, common_prefixes: List[str] = [],
                                   next_marker: Optional[str] = None):
    """
    生成 ListObjects 的 XML 响应内容
    """
    content = f"""<?xml version="1.0" encoding="UTF-8"?>
<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  <Name>{bucket}</Name>
  <IsTruncated>{"true" if is_truncated else "false"}</IsTruncated>
  <Prefix>{prefix}</Prefix>
  <MaxKeys>{max_keys}</MaxKeys>
"""
    if next_marker:
        content += f"  <NextMarker>{next_marker}</NextMarker>\n"

    for prefix_str in common_prefixes:
        prefix_str = prefix_str.replace("\\", "/")
        content += f"""  <CommonPrefixes>
    <Prefix>{prefix_str}</Prefix>
  </CommonPrefixes>
"""

    for obj in objects:
        obj = obj.replace("\\", "/")
        obj_path = Path(STORAGE_DIR) / bucket / obj
        last_modified = datetime.datetime.fromtimestamp(obj_path.stat().st_mtime).strftime('%Y-%m-%dT%H:%M:%SZ')
        content += f"""  <Contents>
    <Key>{obj}</Key>
    <LastModified>{last_modified}</LastModified>
    <ETag></ETag>
    <Size>{obj_path.stat().st_size}</Size>
    <StorageClass>STANDARD</StorageClass>
  </Contents>
"""

    content += f"  <KeyCount>{len(objects)}</KeyCount>\n"
    content += '  <EncodingType>url</EncodingType>\n'
    content += "</ListBucketResult>"
    return content
